package org.hot100.h206;

/**
 * @Author: wjy
 * @Date: 2022/2/9 10:24
 */
public class Solution {

    public static void main(String[] args) {

        ListNode listNode5 = new ListNode(5);
        ListNode listNode4 = new ListNode(4, listNode5);
        ListNode listNode3 = new ListNode(3, listNode4);
        ListNode listNode2 = new ListNode(2, listNode3);
        ListNode listNode1 = new ListNode(1, listNode2);
        ListNode listNode0 = new ListNode(0, listNode1);

        Solution solution = new Solution();
        ListNode listNode = solution.reverseList3(listNode0);

        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }

    public ListNode reverseList(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }

        ListNode inversion = new ListNode();
        ListNode temp = head.next;
        ListNode node = null;
        ListNode next = head.next.next;

        while (true) {
            temp.next = node;
            inversion.next = temp;
            node = inversion.next;
            temp = next;
            if (next == null) {
                break;
            }
            next = next.next;
        }

        return inversion.next;

    }

    public ListNode reverseList2(ListNode head) {
        //申请节点，pre和 cur，pre指向null
        ListNode pre = null;
        ListNode cur = head;
        ListNode tmp = null;
        while(cur!=null) {
            //记录当前节点的下一个节点
            tmp = cur.next;
            //然后将当前节点指向pre
            cur.next = pre;
            //pre和cur节点都前进一位
            pre = cur;
            cur = tmp;
        }
        return pre;
    }

    public ListNode reverseList3(ListNode head) {
        ListNode temp = null, cur = head, next = null;

        while (cur != null) {
            next = cur.next;
            cur.next = temp;
            temp = cur;
            cur = next;
        }

        return temp;
    }

}

class ListNode {

    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

}